﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Deer;
using Deer.Log;

namespace Telex;

sealed class RpcServer : ARpcService, IRpcServer
{
    public RpcServer(ILogger logger, SslServerConfig sslServerConfig, string secretkey, ProtocolMap protocolMap, ActionAsync<RpcHost, ServiceKind> channelActiveFunc, ActionAsync<RpcHost, ServiceKind> channelInactiveFunc)
        : base(logger, protocolMap, channelActiveFunc, channelInactiveFunc)
    {
        this.secretkey = secretkey;
        this.sslServerConfig = sslServerConfig;
    }

    private string secretkey;
    private SslServerConfig sslServerConfig;
    private List<TcpServer> serverArr = new List<TcpServer>();

    protected override ServiceKind CurrentKind
    {
        get { return ServiceKind.SERVER; }
    }
    
    public async ValueTask<EndPoint> BindAsync(IPEndPoint point, RpcHost host)
    {
        if (point == null)
            point = new IPEndPoint(IPAddress.Any, 0);
        if (host.IsEmpty())
            throw new ArgumentNullException(nameof(host));
        
        var server = new TcpServer(sslServerConfig, secretkey, host);
        server.OnConnect += this.OnConnectEvent;
        server.OnDisconnect += this.OnDisconnectEvent;
        await server.BindAsync(point);
        this.serverArr.Add(server);
        return server.BindEndPoint;
    }
    
    public override async ValueTask StopAsync()
    {
        foreach (var server in serverArr)
        {
            await server.StopAsync();
        }
        this.serverArr.Clear();

        await base.StopAsync();
    }
}